package cn.zj.logistics.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.zj.logistics.mapper.OrderDetailMapper;
import cn.zj.logistics.mapper.OrderMapper;
import cn.zj.logistics.pojo.Order;
import cn.zj.logistics.pojo.OrderDetail;
import cn.zj.logistics.pojo.OrderDetailExample;
import cn.zj.logistics.pojo.OrderDetailExample.Criteria;
import cn.zj.logistics.pojo.OrderExample;
import cn.zj.logistics.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	
	
	/*
	 * 
	 * 删除订单数据同时还需要删除订单明细
	 * 一定要在业务层同时操作
	 * Spring的事务在Service处理的（要么都成功，要么都失败）
	 * 
	 */
	@Override
	public int deleteByPrimaryKey(Long orderId) {
		
		//1.删除订单信息
		int row = orderMapper.deleteByPrimaryKey(orderId);
		
		//2.再根据订单的id删除对应的订单明细数据
		OrderDetailExample example = new  OrderDetailExample();
		Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(orderId);
		
		orderDetailMapper.deleteByExample(example);
		
		return row;
	}

	/*
	 * 新增订单思路
	 * 
	 * 1，先将订单基本信息插入到订单表中
	 * 1.1并且获取自动生成的主键（因为订单明细有一个订单id要设置，订单明细属于哪个订单的）
	 * 
	 * 2,获取订单的所有订单明细，为每个订单明细设置获取订单id
	 * 
	 */
	@Override
	public int insert(Order order) {
		
		System.out.println("插入前 ："+order);
		int row = orderMapper.insert(order);
		System.out.println("插入后 ："+order);
		
		List<OrderDetail> orderDetails = order.getOrderDetails();
		for (OrderDetail orderDetail : orderDetails) {
			System.out.println("设置订单id前 ："+orderDetail);
			//设置订单明细的订单id
			orderDetail.setOrderId(order.getOrderId());
			System.out.println("设置订单id后 ："+orderDetail);
			
			//将订单明细插入到数据库
			orderDetailMapper.insert(orderDetail);
		}
		
		
		return row;
		
		
	}

	@Override
	public List<Order> selectByExample(OrderExample example) {
		return orderMapper.selectByExample(example);
	}

	@Override
	public Order selectByPrimaryKey(Long orderId) {
		return orderMapper.selectByPrimaryKey(orderId);
	}

	@Override
	public int updateByPrimaryKeySelective(Order record) {
		return orderMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<OrderDetail> selectDetailsByOrderId(Long orderId) {
		
		OrderDetailExample example = new OrderDetailExample();
		Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(orderId);
		List<OrderDetail> details = orderDetailMapper.selectByExample(example);
		
		return details;
	}

}
